/**
 * 
 */
package com.gwcloud.leetcode.tags.array;

import java.util.Arrays;

/**
 * @ClassName   : Leetcode0016 
 * @author      : ganwei 
 * @date        : 2020年5月12日
 * @Description : Leetcode0016 最接近的三数之和
 */
public class Leetcode0016 {
	int result = 0;
	int mul = Integer.MAX_VALUE;
	/**
	 * -数组貌似没有小超，就得自己刷
	 */
    public int threeSumClosest(int[] nums, int target) {
    	
    	backtrack(nums, 0, 0, target,  0);
    	return result;
    }
    
    /**
     * 可以用回溯
     */
    public void backtrack(int[] nums, int sum, int start, int target, int k) {
    	if(k == 3) {
    		if(Math.abs(sum-target) < mul){
    			result = sum;
    			mul = Math.abs(sum-target);
    		}
    		return;
    	}
    	
    	for(int i = start; i < nums.length; i++){
    		sum += nums[i];  		
    		backtrack(nums, sum, i+1, target, k+1);
    		sum -= nums[i];
    	}
    	
    }
    
    /**
     * 性能好点的算法
     */
    public int threeSumClosest_1(int[] nums, int target) {
    	Arrays.sort(nums);
    	int ans = nums[0]+nums[1]+nums[2];
    	for(int i = 0; i < nums.length; i++){
    		int start = i + 1, end = nums.length-1;
    		while(start < end){
    			int sum = nums[i] + nums[start] + nums[end];
    			if(Math.abs(target - sum) < Math.abs(target - ans)){
    				ans = sum;
    			}
    			
    			if(sum > target){
    				end--;
    			}else if(sum < target){
    				start++;
    			}else{
    				return ans;
    			}
    		}
    	}
    	return ans;
    }
    
    /**
     * -主函数
     */
    public static void main(String[] args) {
    	Leetcode0016 l0016 = new Leetcode0016();
    	int[] nums = {-1,2,1,-4};
    	//l0016.threeSumClosest_1(nums, 1);
    	System.out.println(l0016.threeSumClosest_1(nums, 1));
    }
}
